import router from '@/router'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { loginApi } from '@/api/user'
import { Message } from 'element-ui'
export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userList: [],
      userInfo: {}
    }
  },
  mutations: {
    // 1. 存token
    SET_TOKEN(state, token) {
      // 1.1 往本地存储token
      setToken(token)
      // 1.2 往state中存储token
      state.token = token
    },
    // 2. 删除token
    REMOVE_TOKEN(state) {
      removeToken()
      state.token = null
    },
    // 5. 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    // 6. 清空用户信息
    CLEAR_USER_INFO(state) {
      state.userInfo = {}
    }

  },
  actions: {
    // 1. 登录
    async login(context, { username, password, isAgree }) {
      if (isAgree) {
        // console.log(isAgree)
        context.commit('SET_USER_INFO', { username, password, isAgree })
      } else {
        context.commit('CLEAR_USER_INFO')
      }
      const token = await loginApi({ username, password })
      context.commit('SET_TOKEN', token.token)
      Message.success('登录成功')
      router.replace('/')
    },
    // 2. 退出登录，删除token
    logout(context) {
      // 清除token
      context.commit('REMOVE_TOKEN')
      // 清除用户信息
      context.commit('CLEAR_USER_LIST')
    }
  }
}

